package com.baizhi.service;

import com.baizhi.dao.UserDao;
import com.baizhi.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * ClassName: MyDetailsServiceImpl
 * Description:
 * Date: 2022/11/03 PM 11:51
 * <p>
 * project: codes
 * package: com.baizhi.service
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    private final UserDao userDao;

    @Autowired
    public MyUserDetailsServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.根据用户名查询用户
        User user = userDao.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 2.获取角色
        user.setRoles(userDao.getRolesByUid(user.getId()));
        return user;
    }
}
